﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutoCADDotNetLibrary.Generator.Receiver;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;

namespace AutoCADDotNetLibrary.Generator
{
    [Generator]
    public class CommandClassAttributeGenerator : ISourceGenerator
    {
        public void Initialize(GeneratorInitializationContext context)
        {
            context.RegisterForSyntaxNotifications(() => new CommandMethodAttributeSyntaxReceiver());
        }

        public void Execute(GeneratorExecutionContext context)
        {
            if (!(context.SyntaxContextReceiver is CommandMethodAttributeSyntaxReceiver receiver && receiver.Types.Count > 0))
                return;

            List<ITypeSymbol> types = receiver.Types.OrderBy(x => x.ToDisplayString()).ToList();

            //生成代码
            StringBuilder source = new StringBuilder("using Autodesk.AutoCAD.Runtime;");
            source.AppendLine();

            string namespaceName = string.Empty;
            foreach (ITypeSymbol type in types)
            {
                if (namespaceName != type.ContainingNamespace.ToDisplayString())
                {
                    source.AppendLine();
                    namespaceName = type.ContainingNamespace.ToDisplayString();
                }
                source.AppendLine($"[assembly: CommandClass(typeof({type.ToDisplayString()}))]");
            }

            context.AddSource("CommandClassAttributeGenerator.g.cs", SourceText.From(source.ToString(), Encoding.UTF8));
        }
    }
}
